package net.khoroshev.wschat.web.validator;

import net.khoroshev.wschat.dao.DataStorageProvider;
import net.khoroshev.wschat.service.auth.AuthService;
import net.khoroshev.wschat.web.View;
import net.khoroshev.wschat.web.auth.FormAuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;


/**
 * Created with IntelliJ IDEA.
 * Created by: vfirstov
 * Date: 18.11.13
 * Time: 14:07
 *
 */


@Component
public class UserValidator  {

    @Autowired
    AuthService authService;

//    @Override
//    public boolean supports(Class<?> aClass) {
//        return FormAuthUser.class.isAssignableFrom(aClass);
//    }


    public void validateSignUp(Object o, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "signup.input.validate.firstName");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "signup.input.validate.lastName");
        validateUserName(errors, true);
        validatePassword(errors);

    }

    public void validateSignIn(Object o, Errors errors) {
        validateUserName(errors, false);
        validatePassword(errors);
    }

    public void validatePassword(final Errors errors) {
        Assert.notNull(errors, "Errors object must not be null");
        String value = (String) errors.getFieldValue(View.PASSWORD);
        if (value == null || value.length() < 4) {
            errors.rejectValue(View.PASSWORD, "signup.input.validate.password", null, null);
        }
    }

    public void validateUserName(final Errors errors, boolean validateExists) {
        Assert.notNull(errors, "Errors object must not be null");
        String value = (String) errors.getFieldValue(View.USER_NAME);
        if (value == null || !StringUtils.hasText(value)) {
            errors.rejectValue(View.USER_NAME, "signup.input.validate.userName", null, null);
            return;
        }

        if (validateExists && authService.userExists(value)) {
            errors.rejectValue(View.USER_NAME, "signup.input.validate.existsUserName", null, null);
        }
    }

}
